<template>
  <div>
    <div id="qrcode" class="qrcode"></div>
    <canvas canvas-id="cav" id="cav" />
    <canvas canvas-id="qr" id="qr" />
    <button class="uni-btn uni-btn-mini" type="primary" @click="printLabel">打印标签</button>
  </div>
</template>

<script>
import { sx_icon } from './icon'
import UQRCode from 'uqrcodejs'
import { PageUtil } from '../../utils/PageUtil'
import { StringUtils } from '../../utils/StringUtils'

const printer = uni.requireNativePlugin('LcPrinter')
const modal = uni.requireNativePlugin('modal')
let globalEvent = uni.requireNativePlugin('globalEvent')

let isPrinterInitialized = false

export default {
  data() {
    return {
      labelSize:{
        width: 360,
        height: 300,
      },
      qrSize:100,
      qrPos:{
        dx:260,
        dy:70
      },
      form:{}
    }
  },
  onLoad(params) {
    let _p = PageUtil.parseParam(params)
    let { row: p } = _p
    Object.entries(p).forEach(([key, value]) => {
      this.$set(this.form, key, value)
    })
    // 添加打印状态监听
    if (!isPrinterInitialized) {
      globalEvent.addEventListener('onPrintCallback', function(e) {
        // uni.showToast({
        //   title: 'state: ' + JSON.stringify(e),
        //   duration: 2000
        // })
        // if (e.key == 0) {
        //   uni.showToast({
        //     title: '打印成功',
        //     duration: 2000
        //   })
        //
        // } else
        if (e.key == 3) {
          uni.showToast({
            title: '缺纸',
            duration: 2000
          })
        }
      })
      // globalEvent.addEventListener('getsupportprint', function(e) {})
    }
    this.initPrinter()
  },
  onReady() {
    this.makeLabel()
  },
  methods: {
    initPrinter() {
      // 调用异步方法
      printer.initPrinter({})
      printer.printEnableMark({
        enable: false
      })
      printer.setConcentration({ //设置打印浓度。font_level 取值范围：1~39。
        level: 20
      })
      printer.setLineSpacing({
        spacing: 1
      })
      printer.setFontSize({
        fontSize: 16
      })
      printer.getsupportprint()
    },
    getPbName(value) {
      const _v = value || ""
      const [v] = _v.split(";")
      return v || ""
    },
    last4Unicode(value) {
      const len = (value || "").split("").length

      if (StringUtils.isEmptyOrNull(value) || len < 4) {
        return ""
      }
      const last4 = value.substring(value.length - 4, value.length)
      return last4
    },
    makeLabel(){
      const {
        bii_name,
        confusionCode,
        deliveryt_no,
        bii_unicode,
        supplierCode,
        deliverytDate
      } = this.form || {}
      let context = uni.createCanvasContext('cav')
      context.drawImage(['data:image/png;base64,', sx_icon].join(''), 0, 0, 360, 50)
      const img_m = 50 + 22
      const left = 12
      const topM = 21
      context.setFontSize(14)
      context.fillText(`物料描述:${this.getPbName(bii_name)}`, left, img_m)
      context.fillText(`物料编码:${confusionCode || ""}`, left, img_m + topM * 1)
      context.fillText(`供应商:${supplierCode || ""}`, left, img_m + topM * 2)
      context.fillText(`发货日期:${deliverytDate || ""}`, left, img_m + topM * 3)
      context.fillText(`序列号:${this.last4Unicode(bii_unicode)|| ""}`, left, img_m + topM * 4)
      context.fillText(`出厂编码:${deliveryt_no|| ""}`, left, img_m + topM * 5)

      const {qrSize} = this
      const {dx,dy} = this.qrPos
      // 获取uQRCode实例
      const qr = new UQRCode()
      // 设置二维码内容
      qr.data = bii_unicode
      // 设置二维码大小，必须与canvas设置的宽高一致
      qr.size = qrSize
      // 调用制作二维码方法
      qr.make()
      let qrcontext = uni.createCanvasContext('qr')
      qr.canvasContext = qrcontext
      qr.drawCanvas()
      // qrcode canvas
      uni.canvasToTempFilePath({
        canvasId: 'qr',
        x: 0,
        y: 0,
        width: qrSize,
        height: qrSize,
        destWidth: qrSize,
        destHeight: qrSize,
        success({ tempFilePath }) {
          // drawing qrcode image to main canvas
          context.drawImage(tempFilePath, dx, dy)
          context.draw()
        }
      })
    },
    printLabel() {
      const {width, height} = this.labelSize
      uni.canvasToTempFilePath({
        canvasId: 'cav',
        x: 0,
        y: 0,
        width,
        height,
        destWidth:width,
        destHeight:height,
        success({ tempFilePath }) {
          const path = plus.io.convertLocalFileSystemURL(tempFilePath) //绝对路径
          const fileReader = new plus.io.FileReader()
          fileReader.readAsDataURL(path)
          fileReader.onloadend = (res) => { //读取文件成功完成的回调函数
            // printer doesn't need the prefix of base64
            const headlessBase64 = res.target.result.replace('data:image/png;base64,', '')
            printer.printBitmap2({
              base64: headlessBase64
            })
            // gap of labels
            printer.printLine({
              line_length: 10
            })
            printer.start()
          }
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
#cav {
  height: 70mm;
  width: 110mm;
  margin: 0 12rpx;
}

#qr {
  opacity: 0;
  position: absolute;
}
</style>

